﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MyCompany.MyProject.Model;

namespace MyCompany.MyProject.WebApi.Filter
{
    /// <summary>
    /// FluentValidateFilter 
    /// </summary>
    public class FluentValidateFilter : IActionFilter
    {
        /// <summary>
        /// 参数验证不通过时候返回自定义错误信息
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            
        }

        /// <summary>
        /// 没有使用到
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var data = new MessageModel<List<string>>();
            if (!context.ModelState.IsValid)
            {
                var errors = context.ModelState.Values.SelectMany(v => v.Errors);
                data.success = false;
                data.response = errors.Select(e => e.ErrorMessage).ToList();
                context.Result = new JsonResult(data);
            }
        }
    }
}
